<?php
declare(strict_types=1);
namespace App\Middleware;
use AlibabaCloud\Vcs\V20200515\VcsApiResolver;
use GuzzleHttp\Client;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
class UserOperateMiddleware implements MiddlewareInterface
{
    /** * @var ContainerInterface */
    protected $container;
    /** * @var RequestInterface */
    protected $request;
    /** * @var HttpResponse */
    protected $response;
    public function __construct(ContainerInterface $container, RequestInterface $request, HttpResponse $response)
    {
        $this->container = $container;
        $this->request = $request;
        $this->response = $response;
    }
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->checkUserOperate($request);
        return $handler->handle($request);
    }
    private function checkUserOperate(ServerRequestInterface $request)
    {
        try {
            if($request->getMethod() == 'POST' || $request->getMethod() == 'DELETE'){
                $action = $this->request->getAttribute(Dispatched::class)->handler->callback;
                //获取请求的
//                list($LongController, $method) = explode('@', $action);
//                if($method != 'create'){
                    $container = ApplicationContext::getContainer();
                    $redisService = $container->get(\Hyperf\Redis\Redis::class);

                    $access_token =  $request->getHeader('Mema-Token')[0];
                    $redisKey = 'userInfo:'.$access_token;
                    $userInfo = $redisService->get($redisKey);
                    $urlInfo = $request->getUri();
                    $url = $urlInfo->getScheme().'://'.$urlInfo->getHost().':'.$urlInfo->getPort().$urlInfo->getPath();
//                    var_dump($userInfo);
                    if(!empty($userInfo)){

                        $userInfo = json_decode($userInfo,true);
                        $insertData = array();
                        $insertData['system_user_id'] = $userInfo['user']['id'];
                        $insertData['real_name'] = $userInfo['user']['real_name'];
                        $insertData['url'] = $url;
                        $insertData['referer'] = !empty($request->getHeader('referer')[0]) ? $request->getHeader('referer')[0] : '';
                        $insertData['params'] = !empty($request->getBody()->getContents()) ? $request->getBody()->getContents() : '';
                        $insertData['ip'] = !empty($request->getServerParams()) ? $this->getIp($request->getServerParams()) : '';
                        $insertData['created_at'] = date('Y-m-d H:i:s',time());
                        $insertData['updated_at'] = date('Y-m-d H:i:s',time());

                        Db::table('system_user_operate_log')->insert($insertData);
                    }
//                }
            }

        }catch (\Exception $e){
            $insertData = array();
            $insertData['real_name'] = 'error';
            $insertData['referer'] = $e->getCode();
            $insertData['url'] = $e->getLine();
            $insertData['params'] = $e->getMessage();
            $insertData['created_at'] = date('Y-m-d H:i:s',time());
            $insertData['updated_at'] = date('Y-m-d H:i:s',time());
            Db::table('system_user_operate_log')->insert($insertData);
        }
    }
    function getIp($res){
        if(isset($res['http_client_ip'])){
            return $res['http_client_ip'];
        }elseif(isset($res['http_x_real_ip'])){
            return $res['http_x_real_ip'];
        }elseif(isset($res['http_x_forwarded_for'])){
            //部分CDN会获取多层代理IP，所以转成数组取第一个值
            $arr = explode(',',$res['http_x_forwarded_for']);
            return $arr[0];
        }else{
            return $res['remote_addr'];
        }
    }
}